package gov.police.diary.controller;

import gov.police.diary.command.EditHeadquaterCommand;
import gov.police.diary.model.PolHeadquater;
import gov.police.diary.service.HeadquaterService;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.portlet.bind.annotation.ActionMapping;
import org.springframework.web.portlet.bind.annotation.RenderMapping;

@Controller
@RequestMapping("VIEW")
public class HeadquaterController {

    @Autowired
    private HeadquaterService headquaterService;

    @ModelAttribute(value = "command")
    public void populateCommand(Model model) {
        EditHeadquaterCommand command = new EditHeadquaterCommand();
        command.setName(headquaterService.getHeadquater().getName());
        model.addAttribute("command", command);
    }

    @RenderMapping(params = "action=editHeadquater")
    public String render(RenderRequest request, RenderResponse response, Model model) {
        return "headquater_view";
    }

    @ActionMapping(params = "action=updateHeadquater")
    public void update(ActionRequest request, ActionResponse response, EditHeadquaterCommand command, Model model) {
        if (command.getName() != null && !command.getName().equals(headquaterService.getHeadquater().getName())) {
            PolHeadquater headquater = headquaterService.getHeadquater();
            headquater.setName(command.getName());
            headquaterService.updateHeadquater(headquater);
        }
        System.out.println("command.getName() = " + command.getName());
        response.setRenderParameter("action", "editHeadquater");
    }
}
